import { Dictionary } from "../Dictionary";

export class Graph {

    isDirected: boolean = false;
    vertices = [];
    adjList = new Dictionary<number, number[]>();
    constructor(isDirected = false/**图是否有向*/) {
        this.isDirected = isDirected;
    }

    addVertex(v) {
        if (this.vertices.indexOf(v) == -1) {
            this.vertices.push(v);
            this.adjList.set(v, []);
        }
    }

    addEdge(v, w) {
        if (!this.adjList.get(v)) {
            this.addVertex(v);
        }
        if (!this.adjList.get(w)) {
            this.addVertex(w);
        }

        this.adjList.get(v).push(w);

        if (!this.isDirected) {
            this.adjList.get(w).push(v);
        }
    }

    getVertices() {
        return this.vertices;
    }

    getAdjList() {
        return this.adjList;
    }

    toString() {
        let s = '';
        for (let i = 0; i < this.vertices.length; i++) {
            s += this.vertices[i] + ' -> ';
            const neighbors = this.adjList.get(this.vertices[i]);
            for (let j = 0; j < neighbors.length; j++) {
                s += neighbors[j] + ' ';
            }
            s += '\n';
        }
        return s;
    }

}